// const {singerDetailTable} = require("./singerDetailTable");

const request = require("request")
const jsdom = require("jsdom")
const { JSDOM } = jsdom
const fs=require("fs")
const {singerDetailTable}=require("./singerDetailTable")
module.exports = {
    singerDetail(req,res) {
        let body = JSON.parse(Object.keys(req.body)[0]);
        // console.log(body.mid)
        singerDetailTable.find({
            singer_mid:body.mid
        }).then(data=>{
            // console.log(data)
            if(Number(data)===0){
                console.log("数据库无数据")
                request({
                    url: `https://i.y.qq.com/n2/m/share/profile_v2/index.html`,
                    qs: {
                        ADTAG: "newyqq.singer",
                        source: "ydetail",
                        singermid: body.mid
                    }
                }, (err, response, data) => {
                    let dom = new JSDOM(data, { runScripts: "dangerously" })
                    let firstPageData = dom.window.firstPageData
                    // console.log(firstPageData)
                    let finalData={};
                    finalData.singer_name=firstPageData.data.name;  //歌手名称
                    finalData.singer_mid = firstPageData.data.singerMid; //歌手mid
                    finalData.singer_id = firstPageData.data.singerId; //歌手id
                    // finalData.singerDesc = firstPageData.data.certificateJumpInfoV2.desc; //歌手简介
                    finalData.songTotalNumber = firstPageData.tabData.song.total; //歌手歌曲总数
                    finalData.fansTotalNumber = firstPageData.data.fansNum; 
                    finalData.songList=[]//预存歌曲信息
                    firstPageData.tabData.song.list.forEach(item=>{
                        finalData.songList.push({
                            songName:item.name,
                            songMid:item.mid,
                            songAlbum:item.album.name
                        })
                    })
                    singerDetailTable.create(finalData).then(()=>{
                        console.log("写入数据库成功")
                    })
                    res.send(finalData)
                })  
            }else{
                res.send(data)
            }
        })
    }   
}
